package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpRseponse;
import com.webserver.vo.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 用来处理注册业务
 */
public class RegServlet {

    static {
        File userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }
    public void service(HttpRequest request, HttpRseponse response){
        System.out.println("RegServlet:开始处理注册...");
        //1获取注册页面上表单提交的上来的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        /*
            做必要的验证工作:
            1:要求上述四项信息必须输入内容,不能为空
            2:年龄输入的内容必须是一个数字(正则表达式验证)
            上述两条只要有一条不满足,就直接给用户响应注册失败的提示页面:
            reg_input_error.html,居中一行字:注册失败,输入信息有误

            都满足才执行下面的注册操作
         */
        File userDir = new File("./users");
        File[] suds = userDir.listFiles();
        for (int i = 0; i < suds.length; i++) {
            String name = suds[i].getName();
            int d = name.indexOf(".");
            name = name.substring(0,d);

            if (username.equals(name)){
                File file = new File("./webapps/myweb/have_user.html");
                response.setEntity(file);
                break;
            }else {
                if(
                        (username!=null  &&  password!=null
                                &&  nickname!=null  && ageStr!=null)
                                &&
                                ageStr.matches("[0-9]{1,2}")
                ){
                    int age = Integer.parseInt(ageStr);
                    User user = new User(username,password,nickname,age);
                    //2将用户信息写入文件保存
                    try(
                            FileOutputStream fos = new FileOutputStream("./users/"+username+".obj");
                            ObjectOutputStream oos = new ObjectOutputStream(fos);
                    ){
                        oos.writeObject(user);
                        //设置response响应注册成功页面
                        File file = new File("./webapps/myweb/reg_success.html");
                        response.setEntity(file);
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }else {
                    File file = new File("./webapps/myweb/reg_input_error.html");
                    response.setEntity(file);
                }
            }
        }



        //3设置response注册成功页面


        System.out.println("RegServlet:注册完毕!");
    }
}
